let pages = document.querySelector('.pages')
function render(){
    let keyword = document.querySelector('input[type="text"]').value
    let getPage = (pages.value -1) * 10 
    axios({
        method:'get',
        url: 'http://student.ayulin.cn:8000',
    })
    .then(res => {
        let studentList = res.data
        len = studentList.length
        studentList = studentList.filter(item => item.stuName.includes(keyword) || item.stuClass.includes(keyword))
        studentList = studentList.slice(getPage,getPage + 10)
        document.querySelector('tbody').innerHTML = studentList.map(item => `
            <tr>
                <td>${item.id}</td>
                <td>${item.stuName}</td>
                <td>${item.stuAge}</td>
                <td>${item.stuClass}</td>
                <td>
                    <input type="button" value="修改" class="update" data-id="${item.id}">
                    <input type="button" value="删除" class="delete" data-id="${item.id}">
                </td>
            </tr>
        `).join('')
    })
    .catch(err => {
        console.log(err);
    })
}

render()

document.querySelector('table').addEventListener('click',(e) => {
    let id = e.target.dataset.id
    if (e.target.className === 'update') {
        location.href = `./bookAddOrUpdate.html?id=${id}`
    }
    if (e.target.className === 'delete') {
        if (confirm(`确定要删除 id 为 ${id} 的学生吗`)) {
            axios({
                method:'delete',
                url: `http://student.ayulin.cn:8000/${id}`,
            }).then(() => {
                document.querySelector(`[data-id="${id}"]`).parentElement.parentElement.remove()
            }).catch(err => {
                console.log(err);
            })
        }
    }
})

document.querySelector('[value="新增"]').addEventListener('click',() => location.href = './bookAddOrUpdate.html')

document.querySelector('[value="筛选"]').addEventListener('click',() => render())

document.querySelector('[placeholder]').addEventListener('keyup',e => {
    if(e.key === 'Enter'){
        render()
    }
})


document.querySelector('[placeholder]').addEventListener('blur',() => render())

document.querySelector('.sub').addEventListener('click',() => {
    pages.value = +pages.value === 1 ? 1 : +pages.value - 1
    render()
})

document.querySelector('.add').addEventListener('click',() => {
    pages.value = +pages.value + 1
    render()
})

pages.addEventListener('blur',() => {
    if(!(+pages.value)){
        pages.value = 1
    }
    if(+pages.value <= 0){
        pages.value = 1
    }
    render()
})